package com.zivwu.mvp.pick.list;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.ListPopupWindow;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.zivwu.mvp.R;
import com.zivwu.mvp.pick.PhotoPicker;
import com.zivwu.utils.device.MediaStoreHelper;
import com.zivwu.utils.device.ToastHelper;
import com.zivwu.utils.device.TransitionHelper;
import com.zivwu.utils.model.Photo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


public class PhotoPickerActivity extends AppCompatActivity
        implements PopupDirectoryListAdapter.ItemClickListener,
        BaseQuickAdapter.OnItemChildClickListener {
    private static final int MAX_SHOW_NUM = 20;

    private static final int COUNT = 3;

    TextView tvPhotoNav;
    FrameLayout flPhotoNav;
    Toolbar toolBar;

    private ListPopupWindow popupWindow;

    private RecyclerView rvPhoto;
    private int canSelectCount = 3;
    private MenuItem menuItem;
    private List<Photo> photos;
    private PhotoAdapter photoAdapter;
    private List<Photo> checkPhotos;
    private CompositeDisposable mDisposable;
    private boolean mPreview;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.quick_activity_photo_picker);
        mDisposable = new CompositeDisposable();
        tvPhotoNav = findViewById(R.id.tv_photo_nav);
        flPhotoNav = findViewById(R.id.fl_photo_nav);
        toolBar = findViewById(R.id.titleBar);
        rvPhoto = findViewById(R.id.rv_list);
        tvPhotoNav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.show();
            }
        });
        toolBar.setTitle("");
        setSupportActionBar(toolBar);
        toolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        checkPhotos = new ArrayList<>();
        initPrams(getIntent().getExtras());
        initFragment();
    }


    protected void initPrams(Bundle extras) {
        if (extras == null)
            return;
        canSelectCount = extras.getInt(PhotoPicker.EXTRA_MAX_COUNT, canSelectCount);
        mPreview = extras.getBoolean(PhotoPicker.EXTRA_OPEN_PREVIEW, true);
    }


    private void initFragment() {
        //获取photos
        Disposable subscribe = Observable.just(this)
                .subscribeOn(Schedulers.io())
                .map(new Function<PhotoPickerActivity, List<Photo>>() {
                    @Override
                    public List<Photo> apply(@NonNull PhotoPickerActivity photoPickerActivity) throws Exception {
                        MediaStoreHelper storeHelper = new MediaStoreHelper(photoPickerActivity);
                        ArrayList<Map.Entry<String, List<Photo>>> entries = storeHelper.getPhotosByModifiedDesc();
                        ArrayList<Photo> photoList = new ArrayList<>();
                        if (entries != null && entries.size() != 0)
                            if (entries.get(0).getValue() != null)
                                photoList = (ArrayList<Photo>) entries.get(0).getValue();
                        initPopupWindow(entries);
                        return photoList;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<Photo>>() {
                    @Override
                    public void accept(List<Photo> listPhotoFragment) throws Exception {
                        initListView(listPhotoFragment);
                        flPhotoNav.setVisibility(View.VISIBLE);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                });
        mDisposable.add(subscribe);

    }


    private void initListView(List<Photo> photos) {
        this.photos = photos;
        photoAdapter = new PhotoAdapter(photos, canSelectCount);
        photoAdapter.setOnItemChildClickListener(this);
        rvPhoto.setAdapter(photoAdapter);
        rvPhoto.setLayoutManager(new GridLayoutManager(this, COUNT));
    }


    private void initPopupWindow(ArrayList<Map.Entry<String, List<Photo>>> entries) {
        PopupDirectoryListAdapter dirAdapter = new PopupDirectoryListAdapter(entries);
        dirAdapter.setItemClickListener(this);
        popupWindow = new ListPopupWindow(this);
        popupWindow.setWidth(ListPopupWindow.MATCH_PARENT);
        popupWindow.setHeight(getResources().getDisplayMetrics().heightPixels / 2);
        //获取焦点
        popupWindow.setAdapter(dirAdapter);
        popupWindow.setModal(true);
        popupWindow.setDropDownGravity(Gravity.BOTTOM);
        popupWindow.setAnchorView(tvPhotoNav);
    }

    @Override
    public void onItemClick(Map.Entry<String, List<Photo>> entry) {
        photos = entry.getValue();
        photoAdapter.setNewData(entry.getValue());
        tvPhotoNav.setText(entry.getKey());
        popupWindow.dismiss();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.ziv_picker_menu, menu);
        menuItem = menu.findItem(R.id.done);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int i = item.getItemId();
        if (i == R.id.done) {
            onComplete();
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }


    private void onComplete() {
        List<Photo> photoList = checkPhotos;
        ArrayList<String> list = new ArrayList<>();
        for (Photo photo : photoList) {
            list.add(photo.getData());
        }
        Intent intent = new Intent();
        intent.putStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS, list);
        setResult(RESULT_OK, intent);
        finish();
    }


    public void onSelected(int size) {
        if (size == 0) {
            menuItem.setEnabled(false);
            menuItem.setTitle(getString(R.string.quick_picker_done));
        } else {
            menuItem.setEnabled(true);
            menuItem.setTitle(getString(R.string.quick_picker_done_with_count, size, canSelectCount));
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        int i = view.getId();
        if (mPreview){

            if (i == R.id.iv_checkbox) {
                onCheckViewClicked(adapter, position);

            } else if (i == R.id.iv_photo) {
                int start;
                if (position - MAX_SHOW_NUM > 0) {
                    start = position - MAX_SHOW_NUM;
                } else {
                    start = 0;
                }

                int end;
                if (position + MAX_SHOW_NUM > photos.size()) {
                    end = photos.size();
                } else {
                    end = position + MAX_SHOW_NUM;
                }

                ArrayList<Photo> list = new ArrayList<>();
                for (int p = start; p < end; p++) {
                    list.add(photos.get(p));
                }


                PhotoPicker.builder()
                        .setPreviewPhoto(list)
                        .setPhotoIndex(position - start)
                        .setOptions(TransitionHelper.getShareBundle(this))
                        .start(this);

            }
        }else {
            onCheckViewClicked(adapter, position);
            if (canSelectCount==1){
                onComplete();
            }
        }


    }


    private void onCheckViewClicked(BaseQuickAdapter adapter, int position) {
        Photo photo = (Photo) adapter.getData().get(position);
        if (photo.isChecked()) {
            //item 已经被选中
            photo.setChecked(false);
            checkPhotos.remove(photo);
        } else {
            singleSelected(adapter);

            if (checkPhotos.size() >= canSelectCount && canSelectCount != 1) {
                //超过可以选择的最大数量
                ToastHelper.showMsg(getString(R.string.quick_out_of_photo_can_select, canSelectCount));
                return;
            }
            photo.setChecked(true);
            checkPhotos.add(photo);
        }
        adapter.notifyDataSetChanged();
        onSelected(checkPhotos.size());
    }

    private void singleSelected(BaseQuickAdapter adapter) {
        if (canSelectCount != 1)
            return;
        if (checkPhotos.size() == 1) {
            Photo photo1 = checkPhotos.get(0);
            photo1.setChecked(false);
            checkPhotos.remove(photo1);
            int indexOf = photos.indexOf(photo1);
            adapter.notifyItemChanged(indexOf);
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable != null)
            mDisposable.dispose();
    }

}
